import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ConstructioninfoService } from '../constructioninfo.service';
import { StorageService } from '../../../../common/storage.service';
import { TimeConfigClass } from "../../../../common/common-config";

@Component({
  selector: 'app-info-constructioninfo-check',
  templateUrl: './check.component.html',
  styleUrls: ['./check.component.css'],
  providers: [ConstructioninfoService],
})

export class InfoConstructioninfoCheckComponent implements OnInit {

  businessId: any; //商机id

  submited: boolean = false; // 后台验证
  isCustomerScan: any = [];//客户是否课件

  checkCol: any = [];  //基础信息表头
  check: any = {};  //基础信息

  standard: any = [];  //施工标准
  standardCol: any = [];  //施工标准表头

  modifyrecord: any = [];  //整改记录

  isShow: boolean = false; //弹窗显隐
  photoImages: any = [];  //弹框图片

  recoverPhoto:any;// 恢复弹框图片
  recoverPhotoImages: any = [];// 恢复弹框图片

  timeConfig: any = new TimeConfigClass(); // 时间空间初始化

  modifyInitData: any = {};  //整改
  formObj: any = {};  //整改
  photoError: any;  //图片上传错误提示
  uploadRrl: string = 'zuul/com-dyrs-mtsp-fileservice/fileservice/fileDFSSave/api'; // 上传图片地址
  checkId;// 施工节点id
  checkList: any[] = []; // 验收标准
  errorFiel: any; //文件大小超标提示
  isPunishShow: boolean = false; // 发起处罚弹出框
  punishmentsData: any = {}; // 传给处罚弹窗的数据
  descriptionRight: boolean = true; // 发起整改 说明错误提示是否显示
  modifyRecordRight: boolean=true; // 发起整改 整改项错误提示是否显示
  deadlineRight: boolean=true; // 发起整改 最后期限错误提示是否显示
  deadlineMin:Date ; // // 发起整改 最后期限最小时间

  constructor(private router: Router, private constructioninfoService: ConstructioninfoService, private routeInfo: ActivatedRoute,
    public storage: StorageService) {

    this.uploadRrl = (this.constructioninfoService.constructioninfoService.baseUrl || 'http://172.18.8.76/') + this.uploadRrl;
  }

  ngOnInit() {
    this.storage.loading();
    this.isCustomerScan = [
      { code: 0, name: '客户不可见' },
      { code: 1, name: '客户可见' }
    ];
    this.checkCol = [
      { field: 'planStartTimeText', title: '预计开始日期' },
      { field: 'factStartTimeText', title: '实际开始时间' },
      { field: 'planEndTimeText', title: '预计完成日期' },
      { field: 'factEndTimeText', title: '实际完成时间' },
      { field: 'planConstructDays', title: '预计施工时长/天' },
      { field: 'factConstructDays', title: '实际施工时长/天' },
      { field: 'isWarn', title: '是否已预警' },
      { field: 'isDelay', title: '是否已延期' },
      { field: 'warningDays', title: '提前预警天数/天' },
      { field: 'delayDays', title: '延期天数/天' },
      { field: 'customOpinion', title: '客户意见' },
      { field: 'customReason', title: '理由' },
    ];
    this.standardCol = [
      { field: 'sortNum', header: '序号', width: '140px' },
      { field: 'content', header: '施工标准', width: '660px' },
    ];

    // 获取路由id
    this.routeInfo.params.subscribe((params) => {
      this.checkId = params['id'];
      this.businessId = params['infoId'];
      // 施工节点初始化
      this.loadDetail()
    });

  }

  loadDetail() {
    this.constructioninfoService.getCheckDetail(this.checkId).then(
      data => {
        this.storage.loadout();
        if (data.result) {
          // 详情
          this.check = data.data.detail
          if (this.check) {
            this.check.isWarn = this.check.isWarn ? '是' : '否'
            this.check.isDelay = this.check.isDelay ? '是' : '否'
          }
          // 验收说明
          this.standard = data.data.standard
          //验收标准
          this.checkList = data.data.check
          if (this.checkList) {
            this.checkList.forEach(item => {
              let photos = item.photosUrl
              let photoArr = []
              if (photos) {
                for (let photo of photos.split(',')) {
                  photoArr = [...photoArr, {
                    source: photo, thumbnail: photo,
                    width: '100px', maxWidth: '800px', title: ''
                  }];
                }
                item.photoArr = photoArr;
              }
            });
          }
          // 操作结果
          this.modifyrecord = data.data.operation
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: data.msg })
        }
      }
    );
  }

  /**
   * tabview能否进行切换
   */
  onChange(event) {
    event.open();
  }

  /**
   * Description: 发起整改弹窗
   * @Note:
   */
  openDialog(checkId,status) {
    this.constructioninfoService.getInfoStatus(this.businessId).then(
      data =>{
        if(data.result){
          if(data.data == 'constructionstatus_180108000006'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！'});
            return false
          }else if(data.data == 'constructionstatus_180108000004'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！'});
            return false;
          }else if(status == "checkstatus_180108000026" || status == "checkstatus_180108000027" || status == "checkstatus_180108000028"){
            this.storage.messageService.emit({ severity: 'error', detail: '此任务还未上传完成结果，无法进行此操作！'});
            return false;
          }else{
            this.isShow = true;
            this.storage.loading();
            this.modifyInitData = {};
            this.formObj = { isCustomScan: 0 };
            this.photoImages = [];
            this.recoverPhoto = null;
            this.recoverPhotoImages = [];
            this.constructioninfoService.getCurrentDate().then((data)=>{
              if (data.result) {
                this.deadlineMin= new Date(data.data.date);
              }else {
                this.storage.messageService.emit({ severity: 'error', detail: '服务器时间获取失败'})
              }
            });
            // 施工节点初始化
            this.constructioninfoService.getCheckModifyInit(checkId).then(
              data => {
                this.storage.loadout();
                if (data.result) {
                  let modifyInitData = data.data;
                  this.modifyInitData.businessOpportunityName = modifyInitData.businessOpportunityName;
                  this.modifyInitData.businessOpportunityCode = modifyInitData.businessOpportunityCode;
                  this.modifyInitData.foremanName = modifyInitData.foremanName;
                  this.modifyInitData.foremanType = modifyInitData.foremanType;
                  this.modifyInitData.foremanCode = modifyInitData.foremanCode;

                  let photos = modifyInitData.photosUrl;
                  let photoArr = [];
                  if (photos) {
                    for (let photo of photos.split(',')) {
                      photoArr = [...photoArr, {
                        source: photo, thumbnail: photo,
                        width: '100px', maxWidth: '800px', title: ''
                      }];
                    }
                    this.formObj['photo'] = modifyInitData.photos;
                    this.photoImages = photoArr;

                    this.recoverPhoto = modifyInitData.photos;
                    this.recoverPhotoImages = photoArr;
                  }
                  this.formObj.checkCheckId = checkId
                } else {
                  this.storage.messageService.emit({ severity: 'error', detail: data.msg })
                }
              });
          }
        }
      }
    );
  }

  /**
   * 刷新恢复弹框图片
   */
  recoverModifyImage() {
    this.formObj['photo'] = this.recoverPhoto;
    this.photoImages = this.recoverPhotoImages;
  }

  /**
   * Description: 发起整改提交
   * @Note:
   */
  submitDialog() {
    if (this.photoError) return
    this.storage.loading();
    this.formObj['foremanCode']=this.modifyInitData.foremanCode;
    this.constructioninfoService.getSaveCheckModify(this.formObj).then(
      data => {
        this.storage.loadout();
        if (data.result) {
          this.isShow = false;
          this.loadDetail();
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        } else {
            this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
        this.submited = false;
      });
  }

  /**
   * 上传9张图片验证
   */
  onSelect9(event, id) {
    if (this.errorFiel && this.errorFiel.length != 0) {
      id.clear();
      this.errorFiel = undefined;
      return
    } else {
      this.errorFiel = undefined;
    }
    if (event.files.length <= (20 - this[id.cancelLabel + 'Images'].length)) {
      event.upload();
      // this[id.cancelLabel + 'Error'] = '';
    } else {
      id.clear();
      this[id.cancelLabel + 'Error'] = '图片最多上传20张';
    }
  }


  /**
   * Description: 图片大小超过指定值
   */
  onSelectError(event, id) {
    this.errorFiel = event;
    let errorType: any = event[0].errorType;
    if (errorType == "typeError") {
      this[id.cancelLabel + 'Error'] = "上传的图片类型错误";
    }
    if (errorType == "maxError") {
      this[id.cancelLabel + 'Error'] = "图片大小超过限制";
    }
  }

  /**
   * 上传你成功以后数据会显并更新对应图片的数据
   * @param event
   * @param f
   */
  onUpload(event, f) {
    const result = JSON.parse(event.xhr.responseText);
    if (result && result.result && result.data) {
      this.formObj[f.cancelLabel] = this.formObj[f.cancelLabel] ? this.formObj[f.cancelLabel] + ',' + result.data.fileCode :
        result.data.fileCode;
      for (let items of result.data.filePath.split(',')) {
        this[f.cancelLabel + 'Images'] = [...this[f.cancelLabel + 'Images'], {
          source: items, thumbnail: items,
          width: '100px', maxWidth: '800px', title: ''
        }];
      }
    }
  }


  /**
   *删除图片并更新对应的图片数据
   * @param event
   * @param f
   */
  removeItem(event, f) {
    let codeArray = this.formObj[f].split(',');
    codeArray.splice(event.index, 1);
    this.formObj[f] = codeArray.join(',');
    this[f + 'Images'] = this[f + 'Images'].filter((val, index) => index !== event.index);
  }

  /**
   * Description: 上传图片验证
   */
  photoCk() {
    if (!this.formObj['photo']) {
      this.photoError = '请上传拍摄图片';
    } else {
      this.photoError = '';
    }
  }

  /**
   * Description: 处罚
   * @param
   */
  punishments(status) {
    this.constructioninfoService.getInfoStatus(this.businessId).then(
      data =>{
        if(data.result){
          if(data.data == 'constructionstatus_180108000006'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！'});
            return false
          }else if(data.data == 'constructionstatus_180108000004'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！'});
            return false;
          }else if(status == "checkstatus_180108000026"){
            this.storage.messageService.emit({ severity: 'error', detail: '该任务还未启动，无法进行此操作！'});
            return false;
          }else{
            this.punishmentsData.infoId = this.businessId;
            this.punishmentsData.triggerType = 'checkId';
            this.punishmentsData.triggerId = this.checkId;
            this.isPunishShow = true;
          }
        }
      }
    );
  }

  /**
   * 修改发起处罚
   */
  changePunishShow(event) {
    this.isPunishShow = event;
  }


}
